<template>
    <div>
        <div class="MoneyResult">
            <div class="flex flexCenter address" v-if="!addressjson.id && !isQuan" @click="toNext('addressMangeSet',{type:0})">
                <img class="h18 mr10" src="../../../assets/matterlineitem_icon.png@2x.png" alt="">
                <span class="16">管理收货地址</span>
            </div>
            <div class="flex flexSpaceB address" v-if="addressjson.id && !isQuan" @click="toNext('addressMangeSet',{type:0})">
                <div class="flex col textL pt5 pl6 w100" style="width:90%;">
                    <h2 class="fs16 lh18 bold">{{addressjson.contact | sliceString(12)}}</h2>
                    <span class="garyColor fs14 lh18 mt4 mb4">收货地址：{{addressjson.address}}</span>
                    <span class="garyColor fs14 lh18">联系电话：{{addressjson.phone}}</span>
                </div>
                <x-icon type="ios-arrow-forward" size="30" class="garyColor"></x-icon>
            </div>

            <!-- 商品详情页面 -->
            <div class="section flex col">
                <div class="flex flexAlignCenter pb10 pt10 vux-1px-b" style="height:7.5rem;" v-for="(item,index) in goodsInfo" :key="index">
                    <img class="secImg" :src="item.imgUrl" alt="">
                    <div class="secDetail flex col textL pl10">
                        <p class="bold">{{item.productName | sliceString(20)}}</p>
                        <span class="garyColor">数量：{{item.number || item.buyNumber}}</span>
                        <span class="price bold">￥ {{item.salePrice}} </span>
                    </div>
                </div>
                <div class="flex flexSpaceB vux-1px-b h40" v-if="proCoupons.length != 0" @click="showPopups">
                    <span class="garyColor">商品优惠</span>
                    <div class="flex flexCenter">
                        <span class="garyColor">优惠 {{vouchersTotal}} 元</span>
                        <x-icon type="ios-arrow-forward" size="20" class="fs12"></x-icon>
                    </div>
                </div>
                <div class="flex flexSpaceB vux-1px-b h40">
                    <span class="garyColor">运费</span>
                    <span class="bold">￥ {{freightTotal}}</span>
                </div>
                <div class="flex flexSpaceB h40">
                    <span class="garyColor">商品金额</span>
                    <span class="bold">￥ {{proTotalSale}}</span>
                </div>
            </div>
            <!-- 底部结算导航 -->
            <div style="height:5rem;background:#f1f2f3;"></div>
            <div class="fixed l0 b0 r0 h50 whiteBg flex flexSpaceB">
                <p class="garyColor ml20 bold">合计金额：<span class="price bold">￥ {{salePriceTotal || '0'}}</span></p>
                <div v-if="resState.code == '00'" class="tijiao pt6 pb7 pl20 pr20 br20 fs16 mr20" @click.stop="payMoney">提交订单</div>
                <div v-else class="tijiaoDefault pt6 pb7 pl20 pr20 br20 fs16 mr20">提交订单</div>
            </div>
        </div>
        <!-- 优惠券弹窗 -->
        <popup v-model="showPopup" height="70%" 
            :popup-style="popupState" @on-hide="bodyFixed(false)" @on-show="bodyFixed(true)">
            <div class="vux-1px-b h40 lh40 fs16 bold">领取优惠</div>
            <div class="scrollView">
                <div class="flex flexSpaceB br10 borderbox discount_list mt10 lh26 p10" v-for="(item,index) in proCoupons" :key="index">
                    <div class="flex col textL">
                        <h2 class="price fs18 mb15">￥{{item.denomination | denomination(item.type)}}</h2>
                        <p class="fs12 counp lh18">{{item.couponName | sliceString(16)}}</p>
                        <p class="fs12 counp lh16">有效期：{{item.validatyBeginDes}}至{{item.validatyEndDes}}</p>
                    </div>
                    <check-icon :value.sync="item.checked" @click.native="checkQuan(item.checked,index)"></check-icon>
                </div>
            </div>
            <div class="bot flex flexCenter">
                <button class="btnDefautl h30 lh30 w100" @click.stop="clickCouponsList(false)">确定</button>
            </div>
        </popup>
        <reg-phone :isShow="showRegNumber" @cancel="cancel" @confirm="confirmCB"></reg-phone>
    </div>
</template>
<script>
import { getAddressList,shoppingOrders,orderCoupon,createShoppingOrders,integralExchangeProduct,isRegister } from 'request';
import { Popup,CheckIcon } from 'vux';
import { Toast,MessageBox } from "mint-ui";
import mixins from 'mixins';
export default {
    name:'goodsResult',
    mixins:[mixins],
    data(){
        let vuxGoodInfo = [...this.$store.state.e.goodsInfo];
        let is = vuxGoodInfo.every(item=>{
            return item.productType == '4';
        })
        return {
            addressjson:{},                         //地址信息
            productType:'1',                        //商品类型
            goodsInfo: vuxGoodInfo,                 //选中的所有商品信息，在vux中取得
            proCoupons:[],                          //优惠券信息列表
            freightTotal:'0.00',                    //快递价格
            vouchersTotal:"0.00",                   //优惠金额
            proTotalSale:'0.00',                    //商品总售价
            salePriceTotal:'0.00',                  //商品最终售价
            showPopup:false,                        //是否显示popup
            resState:{                              //返回数据状态，防止数量不足的情况
                code:'00'
            },
            popupState:{                            //弹窗样式
                borderTopLeftRadius:'1.5rem',
                borderTopRightRadius:'1.5rem',
                background:'white',
                boxSizing:'border-box',
                padding:'0rem 1.5rem 0rem 1.5rem',
            },
            isQuan:is,                              //判断是否全部是优惠券 如果是，则不会显示地址
            isBindPhone:false,                      //是否绑定手机号
            showRegNumber:false,                    //是否显示弹窗
        }
    },
    async created(){
        this.getadress();           //获取地址信息
        this.getProCoupons();        //获取商品优惠券信息
        await isRegister({}).then(res=>{
            if (res.data.result == "7012") {
                this.isBindPhone = false;
            }else{
                this.isBindPhone = true;
            }
        }).catch(err=>console.log(err))
    },
    computed:{
        //返回选中的优惠券信息
        vouchersList(){
            let arr = [];
            this.proCoupons.forEach(item=>{
                if(item.checked){
                    arr.push({
                        userCouponNo: item.userCouponNo,
                        couponNo: item.couponNo,
                    })
                }
            })
            return arr;
        },
        //商品信息列表查询返回
        productList(){
            let arr = [];
            this.goodsInfo.forEach(item=>{
                arr.push({
                    productNo:item.productNo,
                    buyNumber: item.number || item.buyNumber,
                    specId: item.specString,
                    msg:'',
                })
            })
            return arr;
        }
    },
    methods:{
        //获取用户默认地址
        getadress(){
            this.$vux.loading.show({text:'loading'});
            let storeCateId = this.$store.state.b.cateId;
            getAddressList({}).then(res=>{
                this.$vux.loading.hide();
                if(res.rspCode == '0000' && res.data.rspCode == '0000'){
                    res.data.addressList.forEach(item=>{
                        if(storeCateId && storeCateId == item.id){
                            this.addressjson = item;
                            this.$store.commit("deleteCateId");
                        }else{
                            item.isDefault == 0 && (this.addressjson = item);
                        }
                    })
                }
            }).catch(err=>{
                console.log(err);
                this.$vux.loading.hide();
            })
        },
        //获取商品优惠券信息
        getProCoupons(){
            if(this.productList.length != 0){
                shoppingOrders({productList:this.productList}).then(res=>{
                    if(res.rspCode == '0000' && res.data.resultCode == '00'){
                        let data = {...res.data};
                        data.couponList.forEach(item=>{
                            item.checked = data.checkedCouponNo == item.couponNo ? true : false;
                        });
                        this.proCoupons = data.couponList;
                        this.vouchersTotal = data.voucherMaxAmount;
                        this.freightTotal = data.totalFreight;
                        this.salePriceTotal = data.totalAmount;
                        this.proTotalSale = data.salePriceTotal;
                        // this.clickCouponsList();//更新价格
                    }else{
                        res.data.resultCode == '03' && (this.resState.code == '03');
                        MessageBox("", res.data.resultMesg || "数据请求失败");
                    }
                })
            }else{
                this.clickCouponsList();        //更新价格
            }
        },
        //显示弹窗
        showPopups(){
            this.showPopup = true;
        },
        //点击优惠券,控制单选
        checkQuan(val,index){
            let list = [...this.proCoupons];
            if(val){
                list.forEach((item,ind)=>{
                    item.checked = ind == index ? true : false;
                })
                this.proCoupons = list;
            }
            orderCoupon({
                productList: this.productList,
                vouchersList: this.vouchersList
            }).then(res => {
                if(res.rspCode == '0000' && res.data.resultCode == '00'){
                    this.freightTotal = res.data.freightTotal;
                    this.vouchersTotal = res.data.vouchersTotal;
                    this.proTotalSale = res.data.proTotalSale || '0.00';
                    this.salePriceTotal = res.data.salePriceTotal;
                }else{
                    Toast({ message: '请求失败',position: "middle",duration: 1000 });
                }
            });
        },
        //点击优惠券确定，价格更改
        clickCouponsList(type){
            orderCoupon({
                productList: this.productList,
                vouchersList: this.vouchersList
            }).then(res => {
                if(res.rspCode == '0000' && res.data.resultCode == '00'){
                    this.freightTotal = res.data.freightTotal;
                    this.vouchersTotal = res.data.vouchersTotal;
                    this.proTotalSale = res.data.proTotalSale || '0.00';
                    this.salePriceTotal = res.data.salePriceTotal;
                }else{
                    Toast({ message: '请求失败',position: "middle",duration: 1000 });
                }
            });
            this.showPopup = false;
        },
        //提交订单productType
        payMoney(){
            if(!this.addressjson.id && !this.isQuan){
                Toast({ message: '请先设置地址',position: "middle",duration: 2000 });
                return;
            }else if(!this.isBindPhone){
                this.showRegNumber = true;
                return;
            }
            this.$vux.loading.show({ text: "Loading" });
            createShoppingOrders({
                productList:this.productList,
                addressId: this.isQuan ? "" : this.addressjson.id,
                msg: "",
                vouchersList: this.vouchersList
            }).then(res=>{
                this.$vux.loading.hide();
                if(res.rspCode == '0000' && res.data.resultCode == '00'){
                    integralExchangeProduct({ orderNo: res.data.orderNo}).then(resp=>{
                        if(resp.rspCode == '0000' && resp.data.resultCode == '00'){
                            this.$router.push({ path: "/payMoneyEnd" });
                        }else if (resp.data.resultCode == "04") {
                            if (resp.data.content == undefined) {
                                MessageBox("", "支付系统异常");
                                return;
                            }
                            window.open(resp.data.content, "_self");
                        }else {
                            Toast({ message:'支付失败',position:'middle',duration:1000 });
                            this.$router.push({ path:"/payMoneyEnd",query:{failed:true}});
                        }
                    }).catch(error => console.log(error));
                }else{
                    MessageBox('',"订单提交失败");
                }
            }).catch(err=>{
                console.log(err)
                MessageBox("","订单提交失败");
            })
        },
        //取消方法
        cancel(){
            this.showRegNumber = false;
        },
        //确定方法
        confirmCB(){
            this.showRegNumber = false;
            this.isBindPhone = true;
            this.payMoney();
        }
    },
    components:{
        Popup,CheckIcon
    }
}
</script>
<style lang="less" scoped>
@import './index.less';
</style>
